package com.android.datn.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.datn.activities.AHome;
import com.android.datn.helper.JSonCustomException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Toast;

public class CommonUtil {
	public static DisplayMetrics getDisplayMeTrics(Activity activity) {
		DisplayMetrics metrics = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return metrics;
	}

	public static float px2dp(float pxValue, Context context) {

		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float dpValue = pxValue / (metrics.densityDpi / 160f);
		return dpValue;
	}

	public static float dp2px(float dpValue, Context context) {

		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		float pxValue = dpValue * (metrics.densityDpi / 160f);
		return pxValue;
	}

	public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
		int width = bm.getWidth();
		int height = bm.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
				matrix, false);
		return resizedBitmap;
	}

	public static Bitmap getResizedBitmap(Context context, Uri uriOfBitmap,
			int size) throws FileNotFoundException {

		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(context.getContentResolver()
				.openInputStream(uriOfBitmap), null, o);

		final float REQUIRED_SIZE = size;

		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp / 2 < REQUIRED_SIZE && height_tmp / 2 < REQUIRED_SIZE) {
				break;
			}
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}

		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;
		return BitmapFactory.decodeStream(context.getContentResolver()
				.openInputStream(uriOfBitmap), null, o2);

	}

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static byte[] getBytes(Bitmap bitmap) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 0, stream);
		return stream.toByteArray();
	}

	public static Bitmap getImage(byte[] image) {
		return BitmapFactory.decodeByteArray(image, 0, image.length);
	}

	public static void toastNotify(Context context, String message) {

		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(context, message, duration);
		toast.show();
	}

	public static void dialogNotify(Context context, String message) {

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(message).setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}

				});
		AlertDialog alert = builder.create();
		alert.show();

	}

	/**
	 * Convert a String to md5
	 * 
	 * @param password
	 * @return String
	 */
	public static String convertToMD5(String password) {

		MessageDigest md;
		StringBuffer sb = new StringBuffer();

		try {
			md = MessageDigest.getInstance("MD5");
			md.update(password.getBytes());

			byte byteData[] = md.digest();

			for (int i = 0; i < byteData.length; i++) {
				sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16)
						.substring(1));
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static void dialogNotify(Context context, String message,
			String title) {

		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title);
		builder.setMessage(message).setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}

				});
		AlertDialog alert = builder.create();
		alert.show();

	}
	public static JSONObject getJSONFromUrlParams(String url, List<NameValuePair> params)
			throws IOException, JSonCustomException {

		// Making HTTP request
		InputStream is = null;
		JSONObject jObj = null;
		String json = "";
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			httpClient.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
			httpClient.getParams().setParameter(
					CoreConnectionPNames.SO_TIMEOUT, 60000);
			httpPost.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
			httpPost.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
					60000);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw e;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw e;
		} catch (SocketTimeoutException e) {
			// TODO: handle exception
			e.printStackTrace();
			throw new JSonCustomException(
					"Your wireless signal strength so low !", 640);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			throw new JSonCustomException("Not connect network!", 670);
		} catch (HttpHostConnectException e) {
			e.printStackTrace();
			throw new JSonCustomException("Not connect network!", 670);
		} catch (ConnectTimeoutException e) {
			e.printStackTrace();
			throw new JSonCustomException("Not connect network!", 670);
		} catch (NullPointerException e) {
			e.printStackTrace();
			throw new JSonCustomException("Not connect network!", 670);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
			Log.d("jSon12345", json);
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}
		return jObj;

	}
	public static JSONObject getJSONFromUrl(String url)
			throws IOException, JSonCustomException {

		// Making HTTP request
		InputStream is = null;
		JSONObject jObj = null;
		String json = "";
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(null);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			httpClient.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
			httpClient.getParams().setParameter(
					CoreConnectionPNames.SO_TIMEOUT, 60000);
			httpPost.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
			httpPost.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
					60000);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw e;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw e;
		} catch (SocketTimeoutException e) {
			// TODO: handle exception
			e.printStackTrace();
			throw new JSonCustomException(
					"Your wireless signal strength so low !", 640);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			throw new JSonCustomException("Not connect network!", 670);
		} catch (HttpHostConnectException e) {
			e.printStackTrace();
			throw new JSonCustomException("Not connect network!", 670);
		} catch (ConnectTimeoutException e) {
			e.printStackTrace();
			throw new JSonCustomException("Not connect network!", 670);
		} catch (NullPointerException e) {
			e.printStackTrace();
			throw new JSonCustomException("Not connect network!", 670);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}
		return jObj;

	}
}
